package com.xkw.autocode.util;

import javax.servlet.http.HttpServletRequest;

/**
 * IP 工具类
 * @author System
 *
 */
public class IpUtils {
	private static final String UNKNOWN = "unknown";
	private static final char D = ',';
	
    private IpUtils() {
    }

    public static String getIpAddr(HttpServletRequest request) {
        if (request == null) {
            return UNKNOWN;
        }
        
        String ip = request.getHeader("proxy_add_x_forwarded_for");
        if(ip != null && ip.trim().length() > 0 && !UNKNOWN.equalsIgnoreCase(ip)) {
        	if(ip.indexOf(D) != -1) {
        		ip = ip.substring(0, ip.indexOf(D));
        	}
        	return ip;
        }
        
        ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getHeader("X-Forwarded-For");
        }
        if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getHeader("X-Real-IP");
        }

        if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }
}
